package com.neusoft.neumooc.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.neusoft.core.common.BaseController;
import com.neusoft.core.common.conf.Params;
import com.neusoft.core.util.MD5Util;
import com.neusoft.neumooc.service.UserService;
import com.neusoft.neumooc.vo.UserVO;

@Controller
@RequestMapping(value = "/user")
public class UserController extends BaseController {

    @Autowired
    private UserService userService;

    /**
     * 跳转到用户列表页面
     */
    @RequestMapping(value = "/list")
    public String list() {
        return "user/list";
    }

    /**
     * 获取用户列表数据
     */
    @ResponseBody
    @RequestMapping(value = "/listData")
    public Map<String, Object> listData(HttpServletRequest request) {
        Map<String, Object> retMap = new HashMap<String, Object>();
        try {
            String pageNo = request.getParameter("pageNo");
            String pageSize = request.getParameter("pageSize");
            log.debug("获取用户列表参数: pageNo=" + pageNo + ", pageSize=" + pageSize);
            
            List<UserVO> users = userService.getUsers(Integer.parseInt(pageNo), Integer.parseInt(pageSize));
            log.debug("获取到的用户列表: " + users);
            
            retMap.put(Params.RET_CODE, Params.RET_CODE_SUCCESS);
            retMap.put(Params.RET_OBJ, users);
        } catch (Exception e) {
            log.error("获取用户列表失败", e);
            retMap.put(Params.RET_CODE, Params.RET_CODE_ERROR);
            retMap.put(Params.RET_OBJ, "获取用户列表失败");
        }
        return retMap;
    }

    /**
     * 跳转到添加用户页面
     */
    @RequestMapping(value = "/toAdd")
    public String toAdd() {
        return "user/add";
    }

    /**
     * 添加用户
     */
    @ResponseBody
    @RequestMapping(value = "/add")
    public Map<String, Object> add(UserVO userVO) {
        Map<String, Object> retMap = new HashMap<String, Object>();
        try {
            // 检查用户名是否存在
            Map<String, Object> existUser = userService.getUserByName(userVO.getUserName());
            if (existUser != null) {
                retMap.put(Params.RET_CODE, Params.RET_CODE_ERROR);
                retMap.put(Params.RET_OBJ, "用户名已存在");
                return retMap;
            }
            
            // 设置用户ID
            userVO.setUserId(UUID.randomUUID().toString().replace("-", ""));
            // 密码加密
            userVO.setPassword(MD5Util.gen(userVO.getPassword().getBytes()));
            
            boolean result = userService.addUser(userVO);
            if (result) {
                retMap.put(Params.RET_CODE, Params.RET_CODE_SUCCESS);
                retMap.put(Params.RET_OBJ, "添加成功");
            } else {
                retMap.put(Params.RET_CODE, Params.RET_CODE_ERROR);
                retMap.put(Params.RET_OBJ, "添加失败");
            }
        } catch (Exception e) {
            log.error("添加用户失败", e);
            retMap.put(Params.RET_CODE, Params.RET_CODE_ERROR);
            retMap.put(Params.RET_OBJ, "添加用户失败");
        }
        return retMap;
    }

    /**
     * 跳转到编辑用户页面
     */
    @RequestMapping(value = "/toEdit")
    public String toEdit(String userId, Model model) {
        try {
            UserVO user = userService.getUserInfo(userId);
            model.addAttribute("user", user);
        } catch (Exception e) {
            log.error("获取用户信息失败", e);
        }
        return "user/edit";
    }

    /**
     * 更新用户
     */
    @ResponseBody
    @RequestMapping(value = "/update")
    public Map<String, Object> update(UserVO userVO) {
        Map<String, Object> retMap = new HashMap<String, Object>();
        try {
            // 如果密码不为空,则需要加密
            if (userVO.getPassword() != null && !"".equals(userVO.getPassword())) {
                userVO.setPassword(MD5Util.gen(userVO.getPassword().getBytes()));
            }
            
            boolean result = userService.updateUser(userVO);
            if (result) {
                retMap.put(Params.RET_CODE, Params.RET_CODE_SUCCESS);
                retMap.put(Params.RET_OBJ, "修改成功");
            } else {
                retMap.put(Params.RET_CODE, Params.RET_CODE_ERROR);
                retMap.put(Params.RET_OBJ, "修改失败");
            }
        } catch (Exception e) {
            log.error("修改用户失败", e);
            retMap.put(Params.RET_CODE, Params.RET_CODE_ERROR);
            retMap.put(Params.RET_OBJ, "修改用户失败");
        }
        return retMap;
    }

    /**
     * 删除用户
     */
    @ResponseBody
    @RequestMapping(value = "/delete")
    public Map<String, Object> delete(String userId) {
        Map<String, Object> retMap = new HashMap<String, Object>();
        try {
            int result = userService.deleteUser(userId);
            if (result > 0) {
                retMap.put(Params.RET_CODE, Params.RET_CODE_SUCCESS);
                retMap.put(Params.RET_OBJ, "删除成功");
            } else {
                retMap.put(Params.RET_CODE, Params.RET_CODE_ERROR);
                retMap.put(Params.RET_OBJ, "删除失败");
            }
        } catch (Exception e) {
            log.error("删除用户失败", e);
            retMap.put(Params.RET_CODE, Params.RET_CODE_ERROR);
            retMap.put(Params.RET_OBJ, "删除用户失败");
        }
        return retMap;
    }

    /**
     * 更新用户状态
     */
    @ResponseBody
    @RequestMapping(value = "/updateStatus")
    public Map<String, Object> updateStatus(String userId, String status) {
        Map<String, Object> retMap = new HashMap<String, Object>();
        try {
            if ("1".equals(status)) {
                userService.updateStatusOn(userId);
            } else {
                userService.updateStatusOff(userId);
            }
            retMap.put(Params.RET_CODE, Params.RET_CODE_SUCCESS);
            retMap.put(Params.RET_OBJ, "操作成功");
        } catch (Exception e) {
            log.error("更新用户状态失败", e);
            retMap.put(Params.RET_CODE, Params.RET_CODE_ERROR);
            retMap.put(Params.RET_OBJ, "更新用户状态失败");
        }
        return retMap;
    }
} 